<template>
  <div class="register">
    <div class="register-container">
      <div class="register-right">
        <el-form
          ref="registerForm"
          :model="registerForm"
          :rules="registerRules"
          class="register-form"
        >
          <div class="register-header">
            <h3 class="title">欢迎注册安居客</h3>
            <p class="subtitle">创建您的专属账号</p>
          </div>

          <el-form-item prop="username">
            <el-input
              v-model="registerForm.username"
              type="text"
              auto-complete="off"
              placeholder="请输入用户名"
              prefix-icon="el-icon-user"
            >
            </el-input>
          </el-form-item>

          <el-form-item prop="phonenumber">
            <el-input
              v-model="registerForm.phonenumber"
              type="text"
              auto-complete="off"
              placeholder="请输入手机号"
              prefix-icon="el-icon-phone"
              maxlength="11"
            >
            </el-input>
          </el-form-item>

          <el-form-item prop="smsCode">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-input
                  v-model="registerForm.smsCode"
                  auto-complete="off"
                  placeholder="请输入短信验证码"
                  prefix-icon="el-icon-chat-dot-round"
                  maxlength="6"
                >
                </el-input>
              </el-col>
              <el-col :span="8">
                <el-button 
                  :disabled="smsCodeBtnDisabled" 
                  @click="getSmsCode" 
                  class="sms-code-btn"
                  size="medium"
                  type="primary"
                  plain
                >
                  {{ smsCodeBtnText }}
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              auto-complete="off"
              placeholder="请输入密码"
              prefix-icon="el-icon-lock"
              @keyup.enter.native="handleRegister"
              show-password
            >
            </el-input>
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              auto-complete="off"
              placeholder="请再次输入密码"
              prefix-icon="el-icon-lock"
              @keyup.enter.native="handleRegister"
              show-password
            >
            </el-input>
          </el-form-item>

          <el-form-item prop="code" v-if="captchaEnabled">
            <el-row :gutter="10">
              <el-col :span="16">
                <el-input
                  v-model="registerForm.code"
                  auto-complete="off"
                  placeholder="请输入验证码"
                  prefix-icon="el-icon-key"
                  @keyup.enter.native="handleRegister"
                >
                </el-input>
              </el-col>
              <el-col :span="8">
                <img :src="codeUrl" @click="getCode" class="register-code-img" />
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item>
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              class="register-btn"
              @click.native.prevent="handleRegister"
            >
              <span v-if="!loading">立即注册</span>
              <span v-else>注册中...</span>
            </el-button>
          </el-form-item>

          <div class="register-footer">
            <span>已有账号？</span>
            <router-link class="login-link" :to="'/login'">立即登录</router-link>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 底部 -->
    <div class="el-register-footer">
      <span>Copyright © 2024 智慧房产销售系统 All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg, register } from "@/api/login"

export default {
  name: "Register",
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"))
      } else {
        callback()
      }
    }
    return {
      title: process.env.VUE_APP_TITLE,
      codeUrl: "",
      registerForm: {
        username: "",
        phonenumber: "",
        smsCode: "",
        password: "",
        confirmPassword: "",
        code: "",
        uuid: ""
      },
      smsCodeBtnText: "获取验证码",
      smsCodeBtnDisabled: false,
      smsCodeCountdown: 60,
      registerRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, trigger: "blur", message: "请输入您的手机号" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的11位手机号码", trigger: "blur" }
        ],
        smsCode: [
          { required: true, trigger: "blur", message: "请输入短信验证码" },
          { len: 6, message: "验证码长度为6位", trigger: "blur" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\ |", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      captchaEnabled: true
    }
  },
  created() {
    this.getCode()
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img
          this.registerForm.uuid = res.uuid
        }
      })
    },
    getSmsCode() {
      // 验证手机号
      this.$refs.registerForm.validateField('phonenumber', (valid) => {
        if (!valid) {
          // 模拟发送短信验证码
          this.smsCodeBtnDisabled = true
          this.smsCodeBtnText = `${this.smsCodeCountdown}秒后重试`
          
          const timer = setInterval(() => {
            this.smsCodeCountdown--
            this.smsCodeBtnText = `${this.smsCodeCountdown}秒后重试`
            
            if (this.smsCodeCountdown <= 0) {
              clearInterval(timer)
              this.smsCodeBtnDisabled = false
              this.smsCodeBtnText = "获取验证码"
              this.smsCodeCountdown = 60
            }
          }, 1000)
          
          // 模拟生成6位验证码
          const mockSmsCode = Math.floor(100000 + Math.random() * 900000).toString()
          this.$message.success(`验证码已发送至您的手机，验证码为：${mockSmsCode}（演示用）`)
        }
      })
    },
    handleRegister() {
      this.$refs.registerForm.validate(valid => {
        if (valid) {
          this.loading = true
          register(this.registerForm).then(res => {
            const username = this.registerForm.username
            this.$alert("<font color='red'>恭喜你，您的账号 " + username + " 注册成功！</font>", '系统提示', {
              dangerouslyUseHTMLString: true,
              type: 'success'
            }).then(() => {
              this.$router.push("/login")
            }).catch(() => {})
          }).catch(() => {
            this.loading = false
            if (this.captchaEnabled) {
              this.getCode()
            }
          })
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-size: cover;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
    "Microsoft YaHei", Arial, sans-serif;
}

.register-container {
  display: flex;
  width: 900px;
  height: 650px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.register-right {
  flex: 1;
  padding: 60px 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.register-form {
  width: 100%;
  max-width: 320px;
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.register-form .el-form-item {
  margin-bottom: 25px;
}

.register-form .el-input__inner {
  height: 45px;
  line-height: 45px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  font-size: 14px;
  transition: all 0.3s ease;
}

.register-form .el-input__inner:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.register-code-img {
  width: 100%;
  height: 45px;
  border-radius: 8px;
  cursor: pointer;
  border: 1px solid #e0e0e0;
}

.register-btn {
  width: 100%;
  height: 45px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.register-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.sms-code-btn {
  width: 100%;
  height: 45px;
  font-size: 14px;
  border-radius: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.register-footer {
  text-align: center;
  margin-top: 30px;
  font-size: 14px;
  color: #666;
}

.login-link {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
}

.login-link:hover {
  text-decoration: underline;
}

.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  background: rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .register-container {
    width: 95%;
    height: auto;
    flex-direction: column;
  }

  .register-right {
    padding: 30px 20px;
  }

  .title {
    font-size: 22px;
  }
}
</style>
